package auth

import (
	auth_dto "auth-service/internal/dto/authDto"
	"auth-service/internal/service/auth"
	"github.com/danfwing/sd-project/pkg/utils"
	"github.com/gin-gonic/gin"
	"log/slog"
)

type AuthHandle struct {
	Service auth.AuthService
}

// Register 用户注册
func (api *AuthHandle) Register(c *gin.Context) utils.Response {
	var req auth_dto.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		slog.Error("bind json error", "err", err)
		return utils.NewErrorResponse(utils.ErrBadRequest)

	}
	code, err := api.Service.Register(&req)
	if err != nil {
		slog.Error("register user failed", "err", err)
		return utils.NewErrorResponse(utils.ErrRegisterUserFailed)
	}
	return utils.Response{
		Code:    utils.StatusCreated,
		Message: "注册成功",
		Data:    code,
	}
}

// Login 用户登录
func (api *AuthHandle) Login(c *gin.Context) utils.Response {
	var req auth_dto.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		slog.Error("bind json error", "err", err)
		return utils.NewErrorResponse(utils.ErrBadRequest)
	}

	resp, err := api.Service.Login(&req, c.ClientIP())
	if err != nil {
		slog.Error("login error", "err", err)
		return utils.NewErrorResponse(utils.ErrUserLoginFailed)
	}
	return utils.Response{
		Code:    utils.StatusOK,
		Message: "登录成功",
		Data:    resp,
	}
}

// 获取验证码
func (api *AuthHandle) SendCode(c *gin.Context) utils.Response {
	uuid := utils.GenerateUUID()
	data := make(map[string]string)
	data["code"] = uuid
	return utils.Response{
		Code:    utils.StatusOK,
		Message: "发送成功",
		Data:    data,
	}
}
